package org.limit.bookServe.utils;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

import static org.limit.bookServe.utils.BaseClass.resourceReader;
import static org.limit.bookServe.utils.SystemConstants.USER_DATA_FILE_NAME;

/**
 * @author 1.
 * @version 1.0
 * @description: 数据输入输出的通道
 * @date 2023/11/4 12:14
 */
public abstract class DataChannel {


    /**
     * @description 数据写入
     * @param t 写入的对象
     * @param filePath 写入对应的文件
     * @return boolean
     * @author 1.
     * @date: 2023/11/4 13:20
     */
    protected static <T> boolean setData(T t, String filePath) {
        try (
                //获取对象输出流
                ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(Paths.get(filePath)))
        ) {
            oos.writeObject(t);
            return true;
        } catch (IOException e) {
            System.out.println(e);
            return false;
        }
    }

    /**
     * @description 从文件中读取数据到内存
     * @param filePath 读取对应的文件
     * @return boolean
     * @author 1.
     * @date: 2023/11/4 13:27
     */
    protected static <T> T readData(String filePath) {
        try (
                //获取对象输入流
                ObjectInputStream ois = new ObjectInputStream(Files.newInputStream(Paths.get(filePath)))
        ) {
            return (T) ois.readObject();
        } catch (EOFException e) {
            System.out.println(e);
//            e.printStackTrace();
            return null;
        } catch (IOException | ClassNotFoundException e) {
            System.out.println(e);
            return null;
        }
    }


}








